﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Text;
using System.Collections;

namespace FOBVT.Web.DBUtility
{
	/// <summary>
	/// 计算数据记录的方法类
	/// </summary>
	internal class CountMethod : BaseMethod
	{
		private static Hashtable CountClauseStore = new Hashtable();
		public CountMethod(Type infoType)
			: base(infoType)
		{
		}
		public CountMethod(BaseInfo info)
			: base(info)
		{
		}
		public CountMethod(string TableName, BaseInfo info)
			: base(TableName, info)
		{
		}

		/// <summary>
		/// 得到表所有记录行数
		/// </summary>
		/// <returns></returns>
		public int Count()
		{
			return Count(null);
		}

		/// <summary>
		/// 得到记录行数
		/// </summary>
		/// <param name="WhereClause">查询条件</param>
		/// <returns></returns>
		public int Count(string WhereClause)
		{
			StringBuilder sb_sql = new StringBuilder();
			sb_sql.Append(this.CountClause);
			if (!string.IsNullOrEmpty(WhereClause))
			{
				sb_sql.AppendFormat(" WHERE {0} ", WhereClause);
			}
			sb_sql.Append(';');
			object resultobj = base.ExecuteScalar(sb_sql.ToString(), null);
			if (resultobj != null)
			{
				return int.Parse(resultobj.ToString());
			}
			return 0;
		}
		/// <summary>
		/// 判断记录是否存在
		/// </summary>
		public bool Exists
		{
			get
			{
				if (!((base.Entity != null) && base.HasIdentity))
				{
					return false;
				}
				return this.Count(base.IdentityWhereClause) > 0;
			}
		}
		/// <summary>
		/// select count(*) from...
		/// </summary>
		public string CountClause
		{
			get
			{
				string result = CountClauseStore[base.TableName] as string;
				if (result == null)
				{
					CountClauseStore[base.TableName] = result = string.Format("SELECT COUNT(*) FROM [{0}]", base.TableName);
				}
				return result;
			}
		}
	}
}